﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MediaScraper.Common;
using MediaScraper.Dashboard.Infrastructure;
using MediaScraper.Dashboard.Models;
using MediaScraper.DataAccess;
using MediaScraper.WindowsService;

namespace MediaScraper.Dashboard.Controllers
{
    public class HomeController : BaseController
    {
        public ActionResult Index()
        {
            var dashboardModel = new DashboardModel {ServiceRunning = ScraperController.IsRunning()};
            return View(dashboardModel);
        }

        [ChildActionOnly]
        public ActionResult RecentActivities()
        {
            ActivityModel activityModel = new ActivityModel();
            
            using (var context = new DataContext())
            {
                var data = context.ProcessHistoryEntries.OrderByDescending(x => x.ProcessDate).Take(10).ToList();
                foreach (var processHistoryEntry in data)
                {
                    activityModel.AddEntry(processHistoryEntry);
                }
            }

            return PartialView("_RecentActivities");
        }

        public ActionResult Start()
        {
            ScraperController.StartService();
            return RedirectToAction("Index");
        }

        public ActionResult Stop()
        {
            ScraperController.StopService();
            return RedirectToAction("Index");}

        public ActionResult Log()
        {
            LogModel m = new LogModel { LogEntries = ReadLogFile ()};
            return View(m);
        }


        private List<string> ReadLogFile()
        {
            var result = new List<string>();

            var directory = new DirectoryInfo(Server.MapPath(@"~/logs/"));
            if (directory.Exists)
            {
                string line;
                var myFile = (from f in directory.GetFiles()
                              orderby f.LastWriteTime descending
                              select f).First();

                StreamReader file =
                   new StreamReader(myFile.FullName);
                while ((line = file.ReadLine()) != null)
                {
                    result.Add(line);
                }

                file.Close();
            }

            return result;
        }


    }
}
